﻿using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace Soul.IdentityServer.Validation
{
    public class GrantValidatorFactory : IGrantValidatorFactory
    {
        private readonly IEnumerable<IGrantValidator> _validators;

        public GrantValidatorFactory(IEnumerable<IGrantValidator> validators)
        {
            _validators = validators;
        }

        public IReadOnlyCollection<string> SupportedGrantTypes => _validators.Select(s => s.GrantType).ToList();

        public async Task ValidateAsync(TokenGrantContext context)
        {
            context.Parameters.Validate(OpenIdConnectParameterNames.GrantType);
            var validator = _validators.Where(a => a.GrantType == context.Parameters.GrantType).FirstOrDefault();
            if (validator == null)
            {
                throw new ValidationException(ValidationErrors.UnsupportedGrantType);
            }
            await validator.ValidateAsync(context);
        }
    }
}
